/**
 * @Author: Brad Demirjian
 */
package edu.arizona.eller.mis.hippo.facade;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import java.net.URL;
import java.net.URLConnection;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

public class EbayFacade /*implements ProductLookup*/{

    public final static String EBAY_APP_ID = "johbackce-7661-4bfa-8500-e836b43e7b5";
    public final static String EBAY_FINDING_SERVICE_URI = "http://svcs.ebay.com/services/search/FindingService/v1?OPERATION-NAME="
            + "{operation}&SERVICE-VERSION={version}&SECURITY-APPNAME="
            + "{applicationId}&GLOBAL-ID={globalId}&keywords={keywords}"
            + "&paginationInput.entriesPerPage={maxresults}";
    public static final String SERVICE_VERSION = "1.0.0";
    public static final String OPERATION_NAME = "findItemsByKeywords";
    public static final String GLOBAL_ID = "EBAY-US";
    public final static int MAX_RESULTS = 10;
    private int maxResults;
    private String operationName;

    public EbayFacade() {
        this.maxResults = MAX_RESULTS;
        operationName = OPERATION_NAME;

    }

    private String createAddress(String tag, String operation) {
    	
    	//replace all of the place-holders
        String address = EbayFacade.EBAY_FINDING_SERVICE_URI;
        address = address.replace("{version}", EbayFacade.SERVICE_VERSION);
        address = address.replace("{operation}", this.operationName);
        address = address.replace("{globalId}", EbayFacade.GLOBAL_ID);
        address = address.replace("{applicationId}", EbayFacade.EBAY_APP_ID);
        address = address.replace("{keywords}", tag);
        address = address.replace("{maxresults}", "" + this.maxResults);

        return address;

    }

    private static String read(String address) throws Exception{

        URL url = new URL(address);
        URLConnection connection = url.openConnection();
        connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8");

        String line;
        String response;

        StringBuilder builder = new StringBuilder();
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        while ((line = reader.readLine()) != null) {
            builder.append(line);
            
        }
        
        response = builder.toString();
       
        return response ;
        
    }
   
    public Document getItemsByKeywords(String tag, String operation){
    	InputStream is = null;
    	if(operation != null){
    		operationName = operation;
    	}
    	
    	String address = createAddress(tag, operationName);
    	
    	try{
     	   String response = read(address);
     	   is = new ByteArrayInputStream(response.getBytes("UTF-8"));
     	   DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
     	   DocumentBuilder builder = domFactory.newDocumentBuilder();
     	   Document doc = builder.parse(is);
     	   
     	   return doc;
     	   
        }catch (Exception e){
     	   e.printStackTrace();
        }finally{
        	if(is != null){
        		try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
        	}
        }
  	   return null;
    }
}
